package com.ww.springboot.es2.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2025-07-30 15:56
 */
@Slf4j
public class JsonPointUtil {

    private final static ObjectMapper mapper = new ObjectMapper();

    /**
     * 根据路径获取json中的值
     *
     * @param json
     * @param path
     * @return
     */
    public static Object jsonPoint(String json, String path) {
        try {
            JsonNode rootNode = mapper.readTree(json);
            // 使用 JsonPointer 查找节点
            JsonNode authorNode = rootNode.at(path);
            if (authorNode.isArray()) {
                List<String> includes = new ArrayList<>();
                authorNode.forEach(node -> includes.add(node.asText()));
                return includes;
            }
            return authorNode.asText();
        } catch (Exception e) {
            log.error("jsonPoint异常", e);
            throw new RuntimeException("jsonPoint异常");
        }
    }

    public static ObjectNode getObjectNode(String jsonStr) throws JsonProcessingException {
        JsonNode rootNode = mapper.readTree(jsonStr);
        return (ObjectNode) rootNode;
    }


}
